package com.fei.spring.rabbitmq.four;
import com.fei.spring.rabbitmq.utils.RabbitMQUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;

import java.util.UUID;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;

public class messageAsync {
    //批量发1000个消息
    public static int MESSAGE_COUNT = 1000;
    public static void main(String[] args) throws Exception {
        Channel channel = RabbitMQUtils.getChannel();
        //队列声明
        String queueName = UUID.randomUUID().toString();
        channel.queueDeclare(queueName,true,false,false,null);
        //开启发布确认
        channel.confirmSelect();

        /*
         * 线程安全有序的哈希表，适用于高并发
         * 功能：
         * 1.将序号与消息进行key:value关联
         * 2.只要给到序号就能批量删除条目
         * 3.支持高并发(多线程)
         * */
        ConcurrentSkipListMap<Long,String> outstandingConfirms = new ConcurrentSkipListMap<>();

        /*
         * 消息确认成功
         * 1.消息的标记
         * 2.是否为批量确认
         * */
        ConfirmCallback confirmCallback = (deliveryTag, multiple) -> {
            //二、批量删除掉已经确认的消息 剩下就是未确认消息
            if (multiple){
                ConcurrentNavigableMap<Long, String> confirmed = outstandingConfirms.headMap(deliveryTag);
                confirmed.clear();//清理已经确认的消息
            }else {
                //单个删除已确认的消息
                outstandingConfirms.remove(deliveryTag);
            }
            System.out.println("确认的消息："+deliveryTag);
        };
        /*
         * 消息确认失败
         * 1.消息的标记
         * 2.是否为批量确认
         * */
        ConfirmCallback nackCallback = (deliveryTag, multiple) -> {
            //三、处理未确认消息 打印
            String message = outstandingConfirms.get(deliveryTag);
            System.out.println("未确认的消息是："+message+"---------未确认的消息标记："+deliveryTag);
        };

        //消息监听器 监听哪些消息发送成功，哪些消息发送失败
        /*
         * 1.监听哪些消息发送成功
         * 2.监听哪些消息发送失败
         * */
        channel.addConfirmListener(confirmCallback,nackCallback);//异步通知

        //开始时间
        long begin = System.currentTimeMillis();
        //批量发送消息
        for (int i = 0; i < MESSAGE_COUNT; i++) {
            String message = "消息" + i;
            channel.basicPublish("",queueName,null,message.getBytes());
            //处理异步未确认消息
            // 一、记录所有要发送的消息 消息的总和
            //channel.getNextPublishSeqNo()：消息序号
            outstandingConfirms.put(channel.getNextPublishSeqNo(),message);
        }

        //结束时间
        long end = System.currentTimeMillis();
        System.out.println("发布"+MESSAGE_COUNT+"个异步确认消息，耗时" + (end - begin) + "ms");

    }
}